package com.seecen.HJM.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.seecen.HJM.enumeration.UserStatusEnum;
import com.seecen.HJM.mapper.UserMapper;
import com.seecen.HJM.model.entity.User;
import com.seecen.HJM.service.IUserManagementService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.time.YearMonth;

@Service
@RequiredArgsConstructor
public class UserManagementServiceImpl implements IUserManagementService {

    private final UserMapper userMapper;


    @Override
    public boolean createUser(User user) {
        // 管理员创建用户时的额外验证
//        validateUserInfo(user);

        // 设置管理员创建的特殊标记
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        user.setUserStatus(UserStatusEnum.ENABLE.getCode());

        return userMapper.insert(user) > 0;
    }

    @Override
    public IPage<User> searchUsers(String keyword, String searchType, Page<User> page) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();

        if (StringUtils.hasText(keyword)) {
            switch (searchType) {
                case "username":
                    queryWrapper.like(User::getUsername, keyword);
                    break;
                case "phone":
                    queryWrapper.like(User::getPhone, keyword);
                    break;
                case "email":
                    queryWrapper.like(User::getEmail, keyword);
                    break;
                default:
                    queryWrapper.and(wrapper -> wrapper
                            .like(User::getUsername, keyword)
                            .or()
                            .like(User::getPhone, keyword)
                            .or()
                            .like(User::getEmail, keyword)
                    );
            }
        }

        queryWrapper.orderByDesc(User::getCreateTime);
        return userMapper.selectPage(page, queryWrapper);
    }

    @Override
    public boolean updateUserByAdmin(Long userId, User user) {
        user.setUserId(userId);
        user.setUpdateTime(LocalDateTime.now());

        // 管理员可以修改所有字段，但需要验证唯一性
        validateUserInfoForUpdate(user);

        return userMapper.updateById(user) > 0;
    }

    @Override
    public boolean resetUserPassword(Long userId, String newPassword) {
        User user = new User();
        user.setUserId(userId);
        user.setPassword(newPassword);
        user.setUpdateTime(LocalDateTime.now());

        return userMapper.updateById(user) > 0;
    }

    @Override
    public boolean manageUserStatus(Long userId, Integer status) {
        User user = new User();
        user.setUserId(userId);
//        user.setUserStatus(UserStatusEnum.values);
//        user.setUserStatus(UserStatusEnum.getByCode(status));
        user.setUpdateTime(LocalDateTime.now());

        return userMapper.updateById(user) > 0;
    }

    @Override
    public long getMonthlyActiveUsers() {
        YearMonth currentMonth = YearMonth.now();
        LocalDateTime startOfMonth = currentMonth.atDay(1).atStartOfDay();
        LocalDateTime endOfMonth = currentMonth.atEndOfMonth().atTime(23, 59, 59);

        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.between(User::getUpdateTime, startOfMonth, endOfMonth)
                .eq(User::getUserStatus, UserStatusEnum.ENABLE);

        return userMapper.selectCount(queryWrapper);
    }

    @Override
    public long getUserTotalCount() {
        return userMapper.selectCount(null);
    }

    @Override
    public User getUserDetail(Long userId) {
        return userMapper.selectById(userId);
    }


    private void validateUserInfo(User user) {
        // 验证用户名唯一性
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, user.getUsername());
        if (userMapper.selectCount(queryWrapper) > 0) {
            throw new RuntimeException("用户名已存在");
        }

        // 验证邮箱唯一性
        if (StringUtils.hasText(user.getEmail())) {
            queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getEmail, user.getEmail());
            if (userMapper.selectCount(queryWrapper) > 0) {
                throw new RuntimeException("邮箱已被注册");
            }
        }

        // 验证手机号唯一性
        if (StringUtils.hasText(user.getPhone())) {
            queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone, user.getPhone());
            if (userMapper.selectCount(queryWrapper) > 0) {
                throw new RuntimeException("手机号已被注册");
            }
        }
    }

    /**
     * 验证用户信息（更新时）
     */
    private void validateUserInfoForUpdate(User user) {
        if (StringUtils.hasText(user.getEmail())) {
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getEmail, user.getEmail())
                    .ne(User::getUserId, user.getUserId());
            if (userMapper.selectCount(queryWrapper) > 0) {
                throw new RuntimeException("邮箱已被其他用户使用");
            }
        }

        if (StringUtils.hasText(user.getPhone())) {
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone, user.getPhone())
                    .ne(User::getUserId, user.getUserId());
            if (userMapper.selectCount(queryWrapper) > 0) {
                throw new RuntimeException("手机号已被其他用户使用");
            }
        }
    }
}

